<template>
	<scroll-view class="container" scroll-y @scroll="handleScroll">
		<view class="grid">
			<view v-for="(item, index) in items" :key="index" :id="'media-' + index" class="media-item">
				<!-- 默认显示图片 -->
				<image v-if="!item.isPlaying" :src="item.img" class="media"></image>
				<!-- 进入中间区域后播放视频 -->
				<!-- #ifdef H5 -->
				<view v-else :id="'video-' + index" class="video-container"></view>
				<!-- #endif  -->
				<!-- #ifdef APP-PLUS -->
				<video id="myVideo" :src="item.video" :poster="videoInfo.img" play-strategy=2 enable-play-gesture
					show-mute-btn autoplay :control="false"></video>
				<!-- #endif  -->
			</view>
		</view>
	</scroll-view>
</template>

<script>
	import Hls from "hls.js";
	import DPlayer from "dplayer";

	export default {
		data() {
			return {
				items: [{
						img: "https://image.maimn.com/cover/dc9c5e72115e56504b3ece307a461181.jpg",
						video: "https://hn.bfvvs.com/play/QdJ0K8Ka/index.m3u8",
						isPlaying: false
					},
					{
						img: "https://image.maimn.com/cover/28beb742d3db60ae6dd9d49cf9cd0997.jpg",
						video: "https://hn.bfvvs.com/play/mbkADgXe/index.m3u8",
						isPlaying: false
					},
					{
						img: "https://image.maimn.com/cover/04514b9893dd1719269aea025015ebe9.jpg",
						video: "https://hn.bfvvs.com/play/vbmDGG9a/index.m3u8",
						isPlaying: false
					}, {
						img: "https://image.maimn.com/cover/dc9c5e72115e56504b3ece307a461181.jpg",
						video: "https://hn.bfvvs.com/play/QdJ0K8Ka/index.m3u8",
						isPlaying: false
					},
					{
						img: "https://image.maimn.com/cover/28beb742d3db60ae6dd9d49cf9cd0997.jpg",
						video: "https://hn.bfvvs.com/play/mbkADgXe/index.m3u8",
						isPlaying: false
					},
					{
						img: "https://image.maimn.com/cover/04514b9893dd1719269aea025015ebe9.jpg",
						video: "https://hn.bfvvs.com/play/vbmDGG9a/index.m3u8",
						isPlaying: false
					}, {
						img: "https://image.maimn.com/cover/dc9c5e72115e56504b3ece307a461181.jpg",
						video: "https://hn.bfvvs.com/play/QdJ0K8Ka/index.m3u8",
						isPlaying: false
					},
					{
						img: "https://image.maimn.com/cover/28beb742d3db60ae6dd9d49cf9cd0997.jpg",
						video: "https://hn.bfvvs.com/play/mbkADgXe/index.m3u8",
						isPlaying: false
					},
					{
						img: "https://image.maimn.com/cover/04514b9893dd1719269aea025015ebe9.jpg",
						video: "https://hn.bfvvs.com/play/vbmDGG9a/index.m3u8",
						isPlaying: false
					},
				],
				videoPlayers: {},
			};
		},
		methods: {
			// 监听滚动，判断哪个元素在中间
			handleScroll() {
				const query = uni.createSelectorQuery().in(this);
				const windowHeight = uni.getSystemInfoSync().windowHeight;

				this.items.forEach((item, index) => {
					const id = `media-${index}`;
					query.select(`#${id}`).boundingClientRect((rect) => {
						if (rect) {
							const centerY = rect.top + rect.height / 2;
							// 判断 centerY 是否位于窗口高度的 40% 到 60% 之间，以确定元素是否处于视口中心。
							const isCenter = centerY > windowHeight * 0.4 && centerY < windowHeight * 0.6;

							if (isCenter && !item.isPlaying) {
								this.$set(this.items, index, {
									...item,
									isPlaying: true
								});
								this.$nextTick(() => {
									this.initVideoPlayer(`video-${index}`, item);
								});
							} else if (!isCenter && item.isPlaying) {
								this.$set(this.items, index, {
									...item,
									isPlaying: false
								});
								this.destroyPlayer(`video-${index}`);
							}
						}
					}).exec();
				});
			},

			// 初始化播放器
			initVideoPlayer(idSelector, item) {
				const container = document.getElementById(idSelector);
				if (!container) return;

				const clips = [
					[60, 70], // 第一个片段：1分钟 - 1分10秒
					[100, 110],
					[160, 170],
					[200, 210],
					[220, 260]
				];

				let currentClipIndex = 0; // 记录当前播放片段索引

				const dp = new DPlayer({
					container: container,
					autoplay: true, // 自动播放
					muted: true, // 静音播放，防止浏览器阻止自动播放
					theme: "#000",
					loop: false, // DPlayer 自己循环，我们自己控制片段循环
					lang: "zh-cn",
					airplay: true,
					screenshot: false,
					hotkey: false,
					preload: "auto", // 预加载
					volume: 0,
					mutex: false, //允许多个播放器同时播放
					video: {
						url: item.video,
						pic: item.img,
						type: "customHls",

						customType: {
							customHls: function(video) {
								if (Hls.isSupported()) {
									const hls = new Hls();
									hls.loadSource(video.src);
									hls.attachMedia(video);
								} else if (video.canPlayType("application/vnd.apple.mpegurl")) {
									video.src = item.video;
								}
							},
						},
						playsInline: true, //允许在内嵌模式下播放
					},
				});
				dp.video.setAttribute("muted", "true");
				dp.video.setAttribute("playsinline", "true");

				dp.on('loadedmetadata', () => {
					dp.video.currentTime = clips[currentClipIndex][0]; // 跳到第一个片段
					dp.play();
				});

				dp.on('timeupdate', () => {
					const currentTime = dp.video.currentTime;
					const [start, end] = clips[currentClipIndex];

					if (currentTime >= end) {
						// 跳转到下一个片段
						currentClipIndex = (currentClipIndex + 1) % clips.length;
						dp.video.currentTime = clips[currentClipIndex][0];
						dp.play();
					}
				});

				this.videoPlayers[idSelector] = dp;
			},

			// 销毁播放器
			destroyPlayer(idSelector) {
				if (this.videoPlayers[idSelector]) {
					this.videoPlayers[idSelector].destroy();
					delete this.videoPlayers[idSelector];
				}
			},
		},
	};
</script>

<style scoped>
	/* 页面滚动容器 */
	.container {
		width: 100vw;
		height: 100vh;
		overflow-y: auto;
		display: flex;
		justify-content: center;
	}

	/* 两列网格布局 */
	.grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 10px;
		padding: 20px;
	}

	/* 每个媒体项 */
	.media-item {
		width: 100%;
		height: 200px;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	/* 图片 */
	.media {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	/* 视频容器 */
	.video-container {
		width: 100%;
		height: 100%;
		position: relative;
		overflow: hidden;
	}

	/* 隐藏DPlayer的控制栏 */
	.video-container /deep/ .dplayer-controller {
		display: none !important;
	}
</style>